package com.hzit.service;

import com.hzit.entity.Users;
import com.hzit.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 类名：
 * 作者：WF
 * 功能：认证逻辑和授权
 */
@Component
public class MyUserDetailService implements UserDetailsService {
	@Autowired
	private UsersMapper usersMapper;

	@Override
	public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
		Users user = new Users();
		user.setUsername(name);
		Users users = usersMapper.selectOne(user);
		if(users == null){
			throw new UsernameNotFoundException("用户名不存在！");
		}
		//角色或权限
		Collection<? extends GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("role,admin,ROLE_user,ROLE_manager,ROLE_chairman");
		// 返回
		return new User(users.getUsername(), users.getPassword(),authorities);
	}
}
